var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
//1.加载passport验证相关模块
var passport = require('passport')

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var productRouter = require('./routes/product')
var commentRouter = require('./routes/comment')
var orderRouter = require('./routes/order')
var addressRouter = require('./routes/address')
// var forumRouter = require('./routes/forum')
var app = express();
//解决跨域问题
app.all('*', function (req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    res.header('Access-Control-Allow-Methods', '*');
    res.header('Content-Type', 'application/json;charset=utf-8');
    next();
  });

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

//2.初始化passport模块
app.use(passport.initialize())

//3.设置passport验证
var JwtStrategy = require('passport-jwt').Strategy,
    ExtractJwt = require('passport-jwt').ExtractJwt;
var opts = {}
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
opts.secretOrKey = 'secret'; //和生成token的签名方法参数保持一致

//4.设置验证方法
passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
    // console.log('token中的数据：',jwt_payload)
    //1.从jwt_payload获取token拥有者的个人信息
    //2.连接数据库mysql,查找是否存在该人，如果是证明该token有效，否则无效
    //2.1 有效，token验证通过
    // console.log("jwt_payload",jwt_payload);
    done(null, jwt_payload)
        //2.2 无效
        // done(new Error('token无效'),null)
}));

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/product', productRouter);
app.use('/comment', commentRouter);
app.use('/order', orderRouter);
app.use('/address', addressRouter);
// app.use('/forum',forumRouter)

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};
    // render the error page
    res.status(err.status || 500);
    res.render('error');
});

module.exports = app;